<?php
namespace Admin\Controller;
use Think\Controller;
use Org\Util\Rbac;
use Think\Page;
class CommonController extends Controller {

    public $loginMarked;
    protected $model;
    /**
      +----------------------------------------------------------
     * 初始化
     * 如果 继承本类的类自身也需要初始化那么需要在使用本继承类的类里使用parent::_initialize();
      +----------------------------------------------------------
     */
    public function _initialize() {

        $systemConfig = include WEB_ROOT . 'Common/Conf/systemConfig.php';
        if (empty($systemConfig['TOKEN']['admin_marked'])) {
            $systemConfig['TOKEN']['admin_marked'] = "http://www.conist.com";
            $systemConfig['TOKEN']['admin_timeout'] = 3600;
            $systemConfig['TOKEN']['member_marked'] = "http://www.conist.com";
            $systemConfig['TOKEN']['member_timeout'] = 3600;
            set_config("systemConfig", $systemConfig, WEB_ROOT . "Common/Conf/");
            if (is_dir(WEB_ROOT . "install/")) {
                //delDirAndFile(WEB_ROOT . "install/", TRUE);
            }
        }
        $this->loginMarked = md5($systemConfig['TOKEN']['admin_marked']);
//         $this->checkLogin();
        // 用户权限检查
        if (C('USER_AUTH_ON') && !in_array(CONTROLLER_NAME, explode(',', C('NOT_AUTH_MODULE')))) {
           // import('ORG.Util.RBAC');
            if (!RBAC::AccessDecision()) {
                //检查认证识别号
                if (!$_SESSION [C('USER_AUTH_KEY')]) {
                    //跳转到认证网关
                    redirect(C('USER_AUTH_GATEWAY'));
//                    redirect(PHP_FILE . C('USER_AUTH_GATEWAY'));
                }
                // 没有权限 抛出错误
                if (C('RBAC_ERROR_PAGE')) {
                    // 定义权限错误页面
                    redirect(C('RBAC_ERROR_PAGE'));
                } else {
                    if (C('GUEST_AUTH_ON')) {
                        $this->assign('jumpUrl', C('USER_AUTH_GATEWAY'));
                    }
                    // 提示错误信息
//                     echo L('_VALID_ACCESS_');
                    $this->error(L('_VALID_ACCESS_'));
                }
            }
        }
        $admin_sub_menu = C('admin_sub_menu.'.CONTROLLER_NAME);
        $this->assign('admin_sub_menu',$admin_sub_menu[ACTION_NAME]);
        
        $this->assign('admin_big_menu',C('admin_big_menu.'.CONTROLLER_NAME));
        $this->assign("menu", $this->show_menu());
        $this->assign("sub_menu", $this->show_sub_menu());
        $this->assign("my_info", $_SESSION['my_info']);
        $this->assign("site", $systemConfig);

      //  $this->getQRCode();
    }

    
    protected function getQRCode($url = NULL) {
        if (IS_POST) {
            $this->assign("QRcodeUrl", "");
        } else {
//            $url = empty($url) ? C('WEB_ROOT') . $_SERVER['REQUEST_URI'] : $url;
            $url = empty($url) ? C('WEB_ROOT') . U(CONTROLLER_NAME . '/' . ACTION_NAME) : $url;
            /*import('QRCode');
            $QRCode = new QRCode('', 80);
            $QRCodeUrl = $QRCode->getUrl($url);
            $this->assign("QRcodeUrl", $QRCodeUrl);*/
        }
    }

    public function checkLogin() {
        if (isset($_COOKIE[$this->loginMarked])) {
            $cookie = explode("_", $_COOKIE[$this->loginMarked]);
            $timeout = C("TOKEN");
            if (time() > (end($cookie) + $timeout['admin_timeout'])) {
                setcookie("$this->loginMarked", NULL, -3600, "/");
                unset($_SESSION[$this->loginMarked], $_COOKIE[$this->loginMarked]);
                $this->error("登录超时，请重新登录", U("Public/index"));
            } else {
                if ($cookie[0] == $_SESSION[$this->loginMarked]) {
                    setcookie("$this->loginMarked", $cookie[0] . "_" . time(), 0, "/");
                    session('elfinder',true);
                } else {
                    setcookie("$this->loginMarked", NULL, -3600, "/");
                    unset($_SESSION[$this->loginMarked], $_COOKIE[$this->loginMarked]);
                    $this->error("帐号异常，请重新登录", U("Public/index"));
                }
            }
        } else {
            $this->redirect("Public/index");
        }
        return TRUE;
    }

    /**
      +----------------------------------------------------------
     * 验证token信息
      +----------------------------------------------------------
     */
    protected function checkToken() {
        if (IS_POST) {
            if (!M("Admin")->autoCheckToken($_POST)) {
               $this->ajaxReturn(array('status' => 0, 'info' => '令牌验证失败'));
            }
            unset($_POST[C("TOKEN_NAME")]);
        }
    }

    /**
      +----------------------------------------------------------
     * 显示一级菜单
      +----------------------------------------------------------
     */
    private function show_menu() {
        $cache = C('admin_big_menu');
        $count = count($cache);
        $i = 1;
        $menu = "";
        foreach ($cache as $url => $name) {
            if ($i == 1) {
                $css = $url == CONTROLLER_NAME || !$cache[CONTROLLER_NAME] ? "fisrt_current" : "fisrt";
                $menu.='<li class="' . $css . '"><span><a href="' . U($url . '/index') . '">' . $name . '</a></span></li>';
            } else if ($i == $count) {
                $css = $url == CONTROLLER_NAME ? "end_current" : "end";
                $menu.='<li class="' . $css . '"><span><a href="' . U($url . '/index') . '">' . $name . '</a></span></li>';
            } else {
                $css = $url == CONTROLLER_NAME ? "current" : "";
                $menu.='<li class="' . $css . '"><span><a href="' . U($url . '/index') . '">' . $name . '</a></span></li>';
            }
            $i++;
        }
        return $menu;
    }

    /**
      +----------------------------------------------------------
     * 显示二级菜单
      +----------------------------------------------------------
     */
    private function show_sub_menu() {
        $big = CONTROLLER_NAME == "Index" ? "Common" : CONTROLLER_NAME;
        $cache = C('admin_sub_menu');
        $sub_menu = array();
        if ($cache[$big]) {
            $cache = $cache[$big];
            foreach ($cache as $url => $title) {
                $url = $big == "Common" ? $url : "$big/$url";
                $sub_menu[] = array('url' => U("$url"), 'title' => $title);
            }
            return $sub_menu;
        } else {
            return $sub_menu[] = array('url' => '#', 'title' => "该菜单组不存在");
        }
    }
    
    
    /**
     * 通用分页列表数据集获取方法
     *
     *  可以通过url参数传递where条件,例如:  index.html?name=asdfasdfasdfddds
     *  可以通过url空值排序字段和方式,例如: index.html?_field=id&_order=asc
     *  可以通过url参数r指定每页数据条数,例如: index.html?r=5
     *
     * @param sting|Model  $model   模型名或模型实例
     * @param array        $where   where查询条件(优先级: $where>$_REQUEST>模型设定)
     * @param array|string $order   排序条件,传入null时使用sql默认排序或模型属性(优先级最高);
     *                              请求参数中如果指定了_order和_field则据此排序(优先级第二);
     *                              否则使用$order参数(如果$order参数,且模型也没有设定过order,则取主键降序);
     *
     * @param boolean      $field   单表模型用不到该参数,要用在多表join时为field()方法指定参数
     * @author 朱亚杰 <xcoolcc@gmail.com>
     *
     * @return array|false
     * 返回数据集
     */
    protected function lists ($model,$where=array(),$order='',$field=true){
        $options    =   array();
        //         $REQUEST    =   (array)I('request.');
        $REQUEST = $_REQUEST;
        if(is_string($model)){
            $model  =   M($model);
        }
    
        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);
    
        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        unset($REQUEST['_order'],$REQUEST['_field']);
    
        if(empty($where)){
            $where  =   array('status'=>array('gt',0));
        }
        if( !empty($where)){
            $options['where']   =   $where;
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        $total        =   $model->where($options['where'])->count();
    
        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = 20;
        }
                $page = new \Think\Page($total, $listRows, $REQUEST);
                if($total>$listRows){
                    $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
//                     $page->setConfig('Admin', '{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}', array("listlong" => "9", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
    
                }
//         $page = $this->page($total, $listRows,1,$REQUEST['r']);
        $p =$page->show();
        $this->assign('page', $p? $p: '');
        $this->assign('total',$total);
        //         dump($page);
        $options['limit'] = $page->firstRow.','.$page->listRows;
    
        $model->setProperty('options',$options);
    
        return $model->field($field)->select();
    }
    
    /**
     * 删除数据,可批量
     * @param unknown $model
     * date:2016年11月22日
     * author: EK_熊
     */
    public function delete($model=''){
        $model = empty($model) ? $this->model : $model;
        $ids = I('request.ids');
        $pk = $model->getPk();
        $map[$pk] = array('in',$ids);
        $ret = $model->where($map)->delete();
        if (!$ret) $this->error('操作失败,网络异常！');
        
        if (method_exists($this,'curd_after')) $this->curd_after();
        $this->success('操作成功！');
    }
    
    /**
     * 批量修改记录状态
     * @param unknown $model
     * @param array $val
     * date:2016年11月22日
     * author: EK_熊
     */
    public function setStatus($model=''){
        $model = empty($model) ? $this->model : $model;
        $ids = I('ids');
        $status = I('request.status');
        $pk = $model->getPk();
        $ret = $model->where([$pk=>['in',$ids]])->save(['status'=>$status,'update_time'=>CURRENT_TIME]);
        if (!$ret) $this->error('操作失败,网络异常！');
        
        if (method_exists($this,'curd_after')) $this->curd_after();
        $this->success('操作成功！');
    }
    
    
    /**
     * 推荐到首页
     *
     * date:2016年12月19日
     * author: EK_熊
     */
    public function setRecommend(){
        $model = empty($model) ? $this->model : $model;
        $ids = I('ids');
        $value = I('request.value');
        $pk = $model->getPk();
        $ret = $model->where([$pk=>['in',$ids]])->save(['is_recommend'=>$value,'update_time'=>CURRENT_TIME]);
        if (!$ret) {
            $this->error('网络异常，操作失败！');
        }
        $this->success('操作完成！');
    }
    
    /**
     * 编辑
     *
     * date:2016年11月22日
     * author: EK_熊
     */
    public function edit(){
    
        $id = I('request.id');
        $pk = $this->model->getPk();
        if (IS_POST){
            $post = I('request.post');
            $post['update_time'] =CURRENT_TIME;
            $where[$pk] = $id;
            $ret = $this->model->where($where)->save($post);
            if (!$ret) $this->error('操作失败！');
            if (method_exists($this,'curd_after')) $this->curd_after();
            $this->success('操作成功！');
        }
        $info = $this->model->where([$pk=>$id])->find();
        $this->assign('admin_sub_menu',"编辑数据[ID：{$id}]");
        $this->assign('status',$this->status);
        $this->assign('info',$info);
        $this->display();
    }
    
    /**
     * 新增
     *
     * date:2016年11月22日
     * author: EK_熊
     */
    public function add(){
    
        if (IS_POST) {
            $post = I('post');
            $post['created_time'] = $post['update_time'] =CURRENT_TIME;
            $ret = $this->model->add($post);
            if (!$ret) $this->error('添加失败！');
            if (method_exists($this,'curd_after')) $this->curd_after();
            $this->success('添加成功！');
        }
    
        $this->assign('status',$this->status);
        $this->display();
    }
    
    /**
     *  排序 排序字段为listorders数组 POST 排序字段为：listorder
     *  author: EK_熊
     */
    protected function _listorders($model) {
        if (!is_object($model)) {
            return false;
        }
        $pk = $model->getPk(); //获取主键名称
        $ids = $_POST['listorders'];
        
        foreach ($ids as $key => $r) {
            $data['listorder'] = $r;
            $model->where(array($pk => $key))->save($data);
        }
        return true;
    }   
    
    /**
     *  排序 排序字段为listorders数组 POST 排序字段为：listorder
     *  author: EK_熊
     */    
    public function listorders() {
        $status = $this->_listorders($this->model);
        if ($status) {
            if (method_exists($this,'curd_after')) $this->curd_after();
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }
    
    public function test(){
        if (method_exists($this,'curd_after')) $this->curd_after();
        
    }
    
    
}